iT邦幫忙

2021 iThome 鐵人賽

DAY 8
0

runBlocking

中文用戶如我們? 直譯一下就是,跑一個塞住

恩,三小?

他真正的意思是,執行一個程式碼區塊,但他的一個特點就是,他真的會塞住,有別於launch和async讓程式碼並聯執行,這個方式開啟的coroutine是為了讓程式碼串聯執行


看看註解,他不應該被coroutine調用,這個設計適用在將一般function帶入以suspend方式撰寫的library, 使用在main functions 和測試 ,詳情和使用方法會在後面的測試章節用到,這邊就簡單帶過。

p.s.因為是新手向的,解釋一下main function,他就是程式開始執行的一個入口,APP應用會有LAUNCH icon,但今天如果寫server,程式會從main開始執行。詳情自己查

withContext

withContext可以在scope裡面切換Dispatcher,並在執行完成後自動切回原本的Dispatcher,再接著執行後面的代碼

和launch和async不同的是,withContext是一個suspend function,作用是透過我們傳入的Dispatcher切換thread,並且我們傳入的context會繼承原有的CoroutineContext,在lambda裡面變成新的CoroutineContext


source code長這樣

For example, if a function makes ten calls to a network, you can tell Kotlin to switch threads only once by using an outer withContext(). Then, even though the network library uses withContext() multiple times, it stays on the same dispatcher and avoids switching threads

至於文檔這一段,我始終沒怎麼看懂,我理解上是

withContext(Dispatcher.IO){
    repeat(10){dosomething()}
}

suspend fun doSomething (){
    withContext (Dispatcher.IO){
}
}

目前理解的意思是,如果有多次執行的Io任務,在外側加上withContext,可以減少thread不斷切換的成本,這是callback function辦不到的,但我對這英文還要琢磨琢磨,如果有想法再回來更新
[文檔](https://developer.android.com/kotlin/coroutines/coroutines-adv)

統整一下

launch async withContext() runBlocking
創建coroutine 創建coroutine 在coroutine裡面切換Dispatcher 創建阻塞的coroutine
內部順序執行 併發、在指定地方拿到回傳 切換thread 測試
結束時不回傳 結束時回傳Deferred 結束時返回原本的Dispatcher 結束時不回傳

上一篇
day7 我不要了,這不是肯德基 cancel
下一篇
day9 Kotlin coroutine 的黑魔法 suspend
系列文
解鎖kotlin coroutine的各種姿勢-新手篇30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言